<template>
    <div>
        <el-card class="box-card" shadow="never">
            <!--导航栏-->
            <el-page-header @back="back" :content="content">
            </el-page-header>
            <el-form ref="form" class="edit-el-form"  :model="form" :rules="rules" label-width="auto">
                <el-form-item label="姓名" prop="realname">
                    <el-input v-model="form.realname" required></el-input>
                </el-form-item>
                <el-form-item label="照片" prop="photo">
                    <Upload :limit="1" :file_list="photo_list" :catch_urls="catch_urls" :remove_urls="remove_urls" :upload_tip="upload_tip"></Upload>
                </el-form-item>
                <el-form-item label="身份证号" prop="id_card">
                    <el-input v-model="form.id_card" maxlength="18" show-word-limit required></el-input>
                </el-form-item>
                <el-form-item label="银行卡号" prop="bank_no">
                    <el-input v-model="form.bank_no" show-word-limit required></el-input>
                </el-form-item>
                <el-form-item label="优抚对象类别" prop="user_type">
                    <div class="block">
                      <el-cascader
                        v-model="form.user_type"
                        :options="allusertype"
                        placeholder="优抚对象类别"
                        collapse-tags
                        style="width:100%"
                        @change="handleUserTypeChange"
                        clearable></el-cascader>
                    </div>
                </el-form-item>

                <el-form-item v-if="showExtendAmount" label="抚恤金金额" prop="extend_amount">
                    <el-input v-model.number="form.extend_amount" show-word-limit required>
                      <template slot="append">元</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="民族" prop="nation">
                  <el-select v-model="form.nation" placeholder="请选择">
                    <el-option
                        v-for="(item,index) in allnations"
                        :key="index"
                        :label="item"
                        :value="index">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="性别">
                    <el-radio-group v-model="form.gender">
                        <el-radio border label="1">男</el-radio>
                        <el-radio border label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model.number="form.age"></el-input>
                </el-form-item>
                <!--查看不展示按钮-->
                <el-form-item v-if="edit_type!=0">
                    <el-button type="primary" @click="submitForm('form')" :loading="loading">{{button_name}}</el-button>
                    <el-button @click="back">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>

    </div>
</template>

<script>
    import { getUserInfo,editUser,getAllNations } from '@/api/user.js'
    import Upload from '@/components/Upload.vue';
    export default {
        name:'UserEdit',
        components:{Upload},
        data() {
            let validateInt=(rule,value,callback)=>{
               if(value==''){
                  callback();
               }
               let int_reg=/^([0-9]{1,})$/;
               let int_arr={
                  age:'年龄',
               };
               let rule_name=int_arr[rule.field];
               if(!int_reg.test(value)){
                  callback(new Error(rule_name+'必须为数字'));
               }else{
                  callback();
               }
            }
            return {
                form: {
                    realname: '',
                    photo: '',
                    id_card:'',
                    bank_no:'',
                    user_type:'',
                    hurt_level:'',
                    hurt_for:'',
                    extend_amount:'',
                    nation:'',
                    gender:'1',
                    age:''
                },
                //校验规则
                rules:{
                    realname: [
                        { required:true , message:'请输入姓名',trigger:'blur' }
                    ],
                    id_card:[
                        { required:true , message:'请输入身份证号',trigger:'blur'}
                    ],
                    bank_no:[
                        { required:true , message:'请输入银行卡号',trigger:'blur'}
                    ],
                    user_type:[
                        { required:true , message:'请选择优抚对象类别',trigger:'blur'}
                    ],
                    age:[
                        { required:false, validator:validateInt,trigger:"blur" }
                    ]
                },
                //加载组件
                loading: false,
                button_name:'立即提交',
                content:'用户添加',
                photo_list:[],
                upload_tip:'只能上传jpg/png/gif文件，且不超过500kb，仅允许上传一张',
                showChildType:false,
                showExtendAmount:false,
                allusertype:this.$store.state.allusertype,
                allchildtype:this.$store.state.allchildtype,
                allhurtfor:[],  //伤残原因
                props: { multiple: true },
                allnations:[]
            }
        },
        methods: {
            submitForm(formName){
                let that = this;
                    this.$refs[formName].validate((valid) => {
                            if (valid) {
                                //将user_type拆分
                                let user_type_arr=this.form.user_type;
                                if(user_type_arr.length>1){
                                    this.form.hurt_level=user_type_arr[1];
                                    this.form.hurt_for=user_type_arr[2];
                                }
                                if(this.form.user_type==11 || this.form.user_type==12){
                                  if(this.form.extend_amount==''){
                                     this.$message.error('请输入抚恤金金额');
                                     return;
                                  }else{
                                     let float_reg=/^([0-9]{1,}[.][0-9]*)$/;
                                     let int_reg=/^([0-9]{1,})$/;
                                     if(!float_reg.test(this.form.extend_amount) && !int_reg.test(this.form.extend_amount)){
                                        this.$message.error('抚恤金金额必须为数字，请检查');
                                        return;
                                     }
                                     if(this.form.extend_amount>100000){
                                        this.$message.error('抚恤金金额不能超过10万元');
                                        return;
                                     }
                                  }
                                }
                                this.form.user_type=user_type_arr[0];
                                this.loading=true;
                                this.button_name='正在提交';
                                var send_data={
                                    realname:this.form.realname,
                                    photo:this.form.photo,
                                    id_card:this.form.id_card,
                                    bank_no:this.form.bank_no,
                                    user_type:this.form.user_type,
                                    hurt_for:this.form.hurt_for,
                                    hurt_level:this.form.hurt_level,
                                    extend_amount:this.form.extend_amount,
                                    nation:this.form.nation,
                                    gender:this.form.gender,
                                    age:this.form.age,
                                };
                                if(this.id!=-1){
                                    send_data.id=this.id;
                                }
                                editUser(send_data).then(function(response){
                                    if(response.data.code==1){
                                         that.$message({
                                             message:that.content+'成功',
                                             type:'success',
                                             duration:1000,
                                             onClose:function(e){
                                                 that.loading=false;
                                                 that.$router.push('/user/userlist');
                                             }
                                         });
                                    }else if(response.data.code==2){
                                        that.$message({
                                            message:'库中已存在同样的身份证号，请勿重复提交',
                                            type:'error',
                                            duration:2000
                                        });
                                        that.loading=false;
                                        that.button_name='立即提交';
                                    }else if(response.data.code==0){
                                        that.$message({
                                            message:that.content+'失败',
                                            type:'error',
                                            duration:2000
                                        });
                                        that.loading=false;
                                        that.button_name='立即提交';
                                    }
                                })
                            }else{
                                setTimeout(()=>{
                                  const is_error=document.getElementsByClassName('is-error');
                                  is_error[0].querySelector('input,button').focus();
                                },100);
                                return false;
                            }
                    })
            },
            back(){
                this.$router.go(-1);
            },
            //这边只有一张，如果有数组就移除数组中的下标
            remove_urls(remove_index){
              if(remove_index==0){
                 this.form.photo=''
              }
            },
            //获取组件返回的图片路径
            catch_urls(urls){
               this.form.photo=urls[0];
            },
            handleUserTypeChange(e){
               if(e[0]==11 || e[0]==12){
                  this.showExtendAmount=true;
               }else{
                  this.showExtendAmount=false;
                  this.form.extend_amount='';
               }
            },
            getUserInfo(){
               if(this.id!=-1){
                   var send_data={
                       id:this.id
                   }
                   let that=this;
                   getUserInfo(send_data).then(function(response){
                       if(response.data.code==1){
                          let val=response.data.info;
                          that.form.realname=val.realname;
                          that.form.photo=val.photo;
                          that.form.id_card=val.id_card;
                          that.form.bank_no=val.bank_no;
                          that.form.gender=val.gender.toString();
                          let user_type_arr=[];
                          let user_type=val.user_type.toString();
                          if(user_type==1){
                              user_type_arr[1]=val.hurt_level;
                              user_type_arr[2]=val.hurt_for;
                          }else if(user_type==11 || user_type==12){
                              that.showExtendAmount=true;
                              that.form.extend_amount=val.extend_amount;
                          }
                          user_type_arr[0]=user_type;
                          that.form.user_type=user_type_arr;
                          that.form.nation=val.nation;
                          that.form.age=val.age==0?'':val.age;
                          if(val.photo!=null && val.photo.length>0){
                            that.photo_list=[{
                                name:0,
                                url:val.photo
                            }];
                          }
                       }
                   })
               }
            }
        },
        created(){
            this.allusertype[0]['children']=this.allchildtype;
            let that=this;
            getAllNations().then(function(response){
               if(response.data.code==1){
                   that.allnations=response.data.list;
                   that.getUserInfo();
               }
            })
            //修改标题
            if(this.edit_type==1){
                this.content='用户添加';
            }else if(this.edit_type==0){
                this.content='用户详情';
            }else if(this.edit_type==2){
                this.content='用户编辑';
            }
        },
        computed:{
            id(){
                return this.$route.params.id;
            },
            edit_type(){
                return this.$route.params.edit_type;
            },
        }
    }
</script>

<style>
    .edit-el-form{
        margin-top:30px;
    }
</style>
